package com.kltn.zigo;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;

import org.json.JSONArray;

import com.kltn.zigo.NewPostActivity.CreateDetailGroupCustomerPlace;
import com.kltn.zigo.NewPostActivity.CreateDetailSpacePlace;
import com.kltn.zigo.NewPostActivity.CreateDetailUtilityPlace;
import com.kltn.zigo.NewPostActivity.CreateNewPlace;
import com.kltn.zigo.NewPostActivity.LoadDistrict;
import com.kltn.zigo.NewPostActivity.LoadGroupCustomer;
import com.kltn.zigo.NewPostActivity.LoadProvince;
import com.kltn.zigo.NewPostActivity.LoadSpacePlace;
import com.kltn.zigo.NewPostActivity.LoadUtility;
import com.kltn.zigo.NewPostActivity.UploadImage;
import com.kltn.zigo.data.IP;
import com.kltn.zigo.data.adapter.DistrictAdapter;
import com.kltn.zigo.data.adapter.GroupCustomerAdapter;
import com.kltn.zigo.data.adapter.PlaceDetailAdapter;
import com.kltn.zigo.data.adapter.ProvinceAdapter;
import com.kltn.zigo.data.adapter.SpacePlaceAdapter;
import com.kltn.zigo.data.adapter.UtilityAdapter;
import com.kltn.zigo.data.delete.DetailGroupCustomerPlaceDelete;
import com.kltn.zigo.data.delete.DetailSpacePlaceDelete;
import com.kltn.zigo.data.delete.DetailUtilityPlaceDelete;
import com.kltn.zigo.data.insert.CommentInsert;
import com.kltn.zigo.data.insert.DetailGroupCustomerPlaceInsert;
import com.kltn.zigo.data.insert.DetailSpacePlaceInsert;
import com.kltn.zigo.data.insert.DetailUtilityPlaceInsert;
import com.kltn.zigo.data.insert.PlaceInsert;
import com.kltn.zigo.data.loader.DistrictLoader;
import com.kltn.zigo.data.loader.GroupCustomerLoader;
import com.kltn.zigo.data.loader.PlaceDetailLoader;
import com.kltn.zigo.data.loader.ProvinceLoader;
import com.kltn.zigo.data.loader.SpacePlaceLoader;
import com.kltn.zigo.data.loader.UtilityLoader;
import com.kltn.zigo.data.update.PlaceUpdate;
import com.kltn.zigo.process.ImageLoader;

import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnDismissListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class UpdatePlaceActivity extends Activity implements OnClickListener {

	private ProgressDialog pDialog;
    Dialog custom;
    Button btnOpenFileDialog;
    
    private MenuItem btnMenu;
    private MenuItem btnSearch;
    private MenuItem btnProfile;
    

    private static LayoutInflater inflater=null;
    public static boolean taskUpdatePlaceFinished = false;
    public static boolean taskInsertGroupCustomerFinished = true;
    public static boolean taskInsertSpacePlaceFinished = true;
    public static boolean taskInsertUtilityFinished = true;
    public static boolean taskDeleteGroupCustomerFinished = true;
    public static boolean taskDeleteSpacePlaceFinished = true;
    public static boolean taskDeleteUtilityFinished = true;
    public static boolean taskUploadAvatarFinished = true;
    
    // Creating JSON Parser object
    //JSONParser jParser = new JSONParser();
 
    ArrayList<HashMap<String, String>> provincesList;
    ArrayList<HashMap<String, String>> districtsList;
    
    ArrayList<HashMap<String, String>> utilitysList;
    ArrayList<HashMap<String, String>> spaceplacesList;
    ArrayList<HashMap<String, String>> groupcustomersList;
    
    ArrayList<String> selectedUtility;
    ArrayList<String> selectedUtilityID;

    ArrayList<String> selectedSpacePlace;
    ArrayList<String> selectedSpacePlaceID;

    ArrayList<String> selectedGroupCustomer;
    ArrayList<String> selectedGroupCustomerID;
    //Adapter

	ProvinceAdapter provinceAdapter;
	DistrictAdapter districtAdapter;
	UtilityAdapter utilityAdapter;	
	SpacePlaceAdapter spacePlaceAdapter;
	GroupCustomerAdapter groupCustomerAdapter;

    private HashMap<String, String> place;
	PlaceDetailAdapter adapter;	
    
    // products JSONArray
    JSONArray jsonArray = null;

	private Button btnSave;
	private Button btnCancel;
	private Button btnAddUtility;
	private Button btnCloseUtility;
	private ImageView imgAvatar;
	
	private EditText edtxtPlaceName;
	private EditText edtxtAddress;
	private EditText edtxtCity;
	private EditText edtxtDistrict;
	private EditText edtxtMapPosition;
	private EditText edtxtPhone;
	private EditText edtxtFax;
	private EditText edtxtEmail;
	private EditText edtxtWebsite;
	private EditText edtxtTimeOpen;
	private EditText edtxtTimeClose;
	private EditText edtxtLowPrice;
	private EditText edtxtHightPrice;
	private EditText edtxtDescription;
	private EditText edtxtUtility;
	private EditText edtxtSpacePlace;
	private EditText edtxtGroupCustomer;      
    ImageLoader imageLoader; 
	

	private int flat = 0;
	
	ListView listProvince;
	ListView listDistrict;
	ListView listUtility;
	ListView listSpacePlace;
	ListView listGroupCustomer;
	
	private int hour;
	private int minute;
    int FILE_PATH = 1; 
    int LOCATION_MAP = 2; 
    
	String place_name = "";
    String address = "";
    String provinceID = "";
    String districtID = "";
    String place_latitude = "";
    String place_longitude = "";
    String phone_number = "";
    String fax_number = "";
    String email = "";
    String website = "";
    String open_time = "";
    String close_time = "";
    String lowest_price = "";
    String hightest_price = "";
    String description = "";
    String avatar_name = "";
    String avatar_name_random = "";
    String avatar_name_random_database = "";
    String avatar_url = "";
    String avatar_path = "";
    
    String utilityID = "";
    String groupCustomerID = "";
    String spacePlaceID = "";
    
    String place_id = "-1";
    
    Button btnSeach;
	String userid;
	String username;
	String userdisplayname;
	String useravatarurl;
    
    //Upload
    TextView messageText;
    int serverResponseCode = 0;
    ProgressDialog dialog = null;
    String upLoadServerUri = IP.get_IP() + IP.get_path_service() +"upload_to_server.php";
    Bitmap bmp;
    String Url_avatar;
    
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_update_place);
		
		ActionBar actionBar = getActionBar();		
		actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#b51d21")));
		
        inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
        edtxtPlaceName = (EditText) findViewById(R.id.edtxt_PlaceName);
		edtxtAddress = (EditText) findViewById(R.id.edtxt_Address);
		edtxtCity = (EditText) findViewById(R.id.edtxt_City);
		edtxtDistrict = (EditText) findViewById(R.id.edtxt_Distrist);
		edtxtMapPosition = (EditText) findViewById(R.id.edtxtMapPosition);
		edtxtPhone = (EditText) findViewById(R.id.edtxt_phone);
		edtxtFax = (EditText) findViewById(R.id.edtxt_fax);
		edtxtEmail = (EditText) findViewById(R.id.edtxtEmail);
		edtxtWebsite = (EditText) findViewById(R.id.edtxtWebsite);
		edtxtTimeOpen = (EditText) findViewById(R.id.edtxt_TimeOpen);
		edtxtTimeClose = (EditText) findViewById(R.id.edtxt_TimeClose);
		edtxtLowPrice = (EditText) findViewById(R.id.edtxt_lowestprice);
		edtxtHightPrice = (EditText) findViewById(R.id.edtxt_hightestprice);
		edtxtDescription = (EditText) findViewById(R.id.edtxt_Description);
		
		edtxtUtility = (EditText) findViewById(R.id.edtxt_Utility);	
		edtxtSpacePlace = (EditText) findViewById(R.id.edtxt_SpacePlace);
		edtxtGroupCustomer = (EditText) findViewById(R.id.edtxt_GroupCustomer);
		
		messageText  = (TextView)findViewById(R.id.messageText);        

		imgAvatar = (ImageView) findViewById(R.id.img_Avatar);
		
		btnSave = (Button) findViewById(R.id.btn_save);		
		btnCancel = (Button) findViewById(R.id.btn_Cancel);
        
		imageLoader=new ImageLoader(getApplicationContext());
		
		selectedUtility = new ArrayList<String>();
	    selectedUtilityID = new ArrayList<String>();

	    selectedSpacePlace = new ArrayList<String>();
	    selectedSpacePlaceID = new ArrayList<String>();

	    selectedGroupCustomer = new ArrayList<String>();
	    selectedGroupCustomerID = new ArrayList<String>();
		//final Activity activityForButton = this;
	    userid = getIntent().getStringExtra("userid");
		username = getIntent().getStringExtra("username");
		userdisplayname = getIntent().getStringExtra("userdisplayname");
		useravatarurl = getIntent().getStringExtra("useravatarurl");
		
	    place_id = getIntent().getStringExtra("placeid");
	    new LoadDetailPlaceAsync().execute();
		
		btnSave.setOnClickListener(this);
		
		btnCancel.setOnClickListener(this);
		
		imgAvatar.setOnClickListener(this);
		
		edtxtCity.setOnClickListener(this);
		
		edtxtDistrict.setOnClickListener(this);
		
		edtxtMapPosition.setOnClickListener(this);
		
		edtxtUtility.setOnClickListener(this);
		
		edtxtSpacePlace.setOnClickListener(this);
		
		edtxtGroupCustomer.setOnClickListener(this);
		
		edtxtTimeOpen.setOnClickListener(this);
		
		edtxtTimeClose.setOnClickListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.update_place, menu);
		btnMenu = menu.findItem(R.id.btn_menu);
		btnSearch = menu.findItem(R.id.btn_search);
		btnProfile = menu.findItem(R.id.btn_profile);
		
		return true;
	}
	
	@Override
	  public boolean onOptionsItemSelected(MenuItem item) {
		 switch (item.getItemId()) {
		   
		    case R.id.btn_profile:
		    {
		    	Intent i=new Intent(getApplicationContext(),ProfileUserActivity.class);
		        i.putExtra("userid", userid);
		        i.putExtra("username", username);
		        i.putExtra("userdisplayname", userdisplayname);
		        i.putExtra("useravatarurl", useravatarurl);
			    startActivity(i);
		    	break;
		    }
		    	
		    case R.id.btn_search:
		    {
		    	Intent i=new Intent(getApplicationContext(),ListPlaceActivity.class);
		    	i.putExtra("userid",userid);
		        i.putExtra("username", username);
		        i.putExtra("userdisplayname", userdisplayname);
		        i.putExtra("useravatarurl", useravatarurl);
			    startActivity(i);
			    break;
		    }
		    
		    case R.id.btn_menu:
		    {
		    	Intent i=new Intent(getApplicationContext(),MainActivity.class);
		        i.putExtra("userid", userid);
		        i.putExtra("username", username);
		        i.putExtra("userdisplayname", userdisplayname);
		        i.putExtra("useravatarurl", useravatarurl);
			    startActivity(i);
		    	break;
		    }
		 }
		 return super.onOptionsItemSelected(item);
	  }

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 1:
			// set time picker as current time
		{
			TimePickerDialog myTPDialog = new TimePickerDialog(this, timePickerListener, hour, minute,false);
			myTPDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Ok",new DialogInterface.OnClickListener() {
			    public void onClick(DialogInterface dialog, int which)
			    {
			        if (which == DialogInterface.BUTTON_POSITIVE)
			        {
			        	flat = 1;
			        }
			    }
			});
			
			myTPDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",new DialogInterface.OnClickListener() {
			    public void onClick(DialogInterface dialog, int which)
			    {
			        if (which == DialogInterface.BUTTON_NEGATIVE)
			        {
			        	flat = 0;
			        	dialog.dismiss();
			        }
			    }
			});
			return myTPDialog;
		}
		case 2:
			// set time picker as current time
			//return new TimePickerDialog(this, timePickerListener1, hour, minute,false);
			//return new TimePickerDialog(this, timePickerListener1, hour, minute, false);
			
			TimePickerDialog myTPDialog = new TimePickerDialog(this, timePickerListener, hour, minute,false);
			myTPDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Ok",new DialogInterface.OnClickListener() {
			    public void onClick(DialogInterface dialog, int which)
			    {
			        if (which == DialogInterface.BUTTON_POSITIVE)
			        {
			        	flat = 2;
			        }
			    }
			});
			myTPDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",new DialogInterface.OnClickListener() {
			    public void onClick(DialogInterface dialog, int which)
			    {
			        if (which == DialogInterface.BUTTON_NEGATIVE)
			        {
			        	flat = 0;
			        	dialog.dismiss();
			        }
			    }
			});
			myTPDialog.setOnDismissListener(new OnDismissListener() {
				
				@Override
				public void onDismiss(DialogInterface dialog) {
					// TODO Auto-generated method stub
					dialog.dismiss();
				}
			});
			return myTPDialog;
 
		}
		return null;
	}
	
	private TimePickerDialog.OnTimeSetListener timePickerListener = 
            new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int selectedHour,
				int selectedMinute) {
			hour = selectedHour;
			minute = selectedMinute; 
			switch(flat)
			{
				case 1:
				{
					open_time =  new StringBuilder().append(pad(hour)).append(":").append(pad(minute)).toString();
					edtxtTimeOpen.setText("Giờ mở cửa: (" + open_time + ")");
					break;
				}
				case 2:
				{
					close_time =  new StringBuilder().append(pad(hour)).append(":").append(pad(minute)).toString();
					edtxtTimeClose.setText("Giờ đóng cửa: (" + close_time + ")");
					break;
				}
				default:break;
			}
		}
	};
 
	private static String pad(int c) {
		if (c >= 10)
		   return String.valueOf(c);
		else
		   return "0" + String.valueOf(c);
	}	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == FILE_PATH) {
	        if (resultCode == RESULT_OK) {
	        	avatar_path = data.getStringExtra("valuePath");
	        	avatar_name = data.getStringExtra("valueName"); 
				avatar_name_random = UUID.randomUUID().toString();
				avatar_name_random_database = avatar_name_random + ".png";
		        avatar_url = IP.get_IP() + IP.get_path_avatar();
	            
	            bmp = BitmapFactory.decodeFile(avatar_path);

				avatar_path = avatar_path.replaceAll(avatar_name, "");
				
	            imgAvatar.setImageBitmap(bmp);
	          }
	      }
		
		if (requestCode == LOCATION_MAP) {
	        if (resultCode == Activity.RESULT_OK) 
	        {
	        	place_latitude = data.getStringExtra("latitude");
	        	place_longitude = data.getStringExtra("longitude"); 

	            edtxtMapPosition.setText(place_latitude + " - " +place_longitude);	           
	          }
	      }
	}

	@SuppressLint("NewApi")
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId())
		{
			case R.id.btn_save:
			{
				place_name = edtxtPlaceName.getText().toString();
		        address = edtxtAddress.getText().toString();
				phone_number = edtxtPhone.getText().toString();
				fax_number = edtxtFax.getText().toString();
				email = edtxtEmail.getText().toString();
				website = edtxtWebsite.getText().toString();
		        lowest_price = edtxtLowPrice.getText().toString();
		        hightest_price = edtxtHightPrice.getText().toString();
		        description = edtxtDescription.getText().toString();
				
				if(!districtID.equals("")&&!place_name.equals("")&&!address.equals("")&&!place_longitude.equals("")&&!place_latitude.equals(""))
				{
					place_name = edtxtPlaceName.getText().toString();
					address = edtxtAddress.getText().toString();
					//String a = avatar_name;
					
					//String b = avatar_path;
					//String c = avatar_url;
	                 	
	                 
					new UpdateInfoPlace().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "");
					new CreateComment().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "");	
					
					if(taskDeleteGroupCustomerFinished == false)
					{
						new DeleteDetailGroupCustomerPlace().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "");
					}
					
					if(taskDeleteSpacePlaceFinished == false)
					{
						new DeleteDetailSpacePlace().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "");
					}
					
					if(taskDeleteUtilityFinished == false)
					{
						new DeleteDetailUtilityPlace().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "");
					}
					
					if(selectedUtilityID.size() > 0)
					{
						taskInsertUtilityFinished = false;
						new CreateDetailUtilityPlace().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "");
					}
					
					if(selectedGroupCustomerID.size() > 0)
					{
						taskInsertGroupCustomerFinished = false;
						new CreateDetailGroupCustomerPlace().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "");
					}
					
					if(selectedSpacePlaceID.size() > 0)
					{
						taskInsertSpacePlaceFinished = false;
						new CreateDetailSpacePlace().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "");	
					}
					
					if(avatar_name != "" && avatar_path != "")
						new UploadImage().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "");
					
					//dialog = ProgressDialog.show(NewPostActivity.this, "", "Uploading file...", true);
					if(avatar_name != "" && avatar_path != "")	
					{
						dialog = ProgressDialog.show(UpdatePlaceActivity.this, "", "Updating place", true);
						taskUploadAvatarFinished = false;
		                new Thread(new Runnable() {
		                        public void run() {
		                             runOnUiThread(new Runnable() {
		                                    public void run() {
		                                        messageText.setText("Uploading started.....");
		                                    }
		                                });                      
		                           
		                             uploadFile(avatar_path + "" + avatar_name);
		                                                      
		                        }
		                      }).start();			
					}
					
					
					
				}				
				else
				{
					if(place_name.equals("")){
						AlertDialog.Builder alert = new AlertDialog.Builder(UpdatePlaceActivity.this);
			    	    alert.setTitle("Bạn chưa nhập tên địa điểm");
			    	    //alert.setMessage("Bạn chưa nhập tên địa điểm");
			    	    alert.show();
					}
					else if(address.equals("")){
						AlertDialog.Builder alert = new AlertDialog.Builder(UpdatePlaceActivity.this);
			    	    alert.setTitle("Bạn chưa nhập địa chỉ địa điểm");
			    	    //alert.setMessage("Bạn chưa nhập địa chỉ địa điểm");
			    	    
			    	    alert.show();
					}
					else if(districtID.equals("")){
						AlertDialog.Builder alert = new AlertDialog.Builder(UpdatePlaceActivity.this);
			    	    alert.setTitle("Bạn chưa chọn quận/huyện");
			    	    //alert.setMessage("Bạn chưa nhập địa chỉ địa điểm");
			    	    
			    	    alert.show();
					}
					else if(place_latitude.equals("")){
						AlertDialog.Builder alert = new AlertDialog.Builder(UpdatePlaceActivity.this);
			    	    alert.setTitle("Bạn chưa xác định vị trí địa điểm trên bản đồ");
			    	    //alert.setMessage("Bạn chưa nhập địa chỉ địa điểm");
			    	    
			    	    alert.show();
					}
				}
				
				break;
			}
			
			case R.id.btn_Cancel:
			{
				/*Intent i=new Intent(UpdatePlaceActivity.this, ListPlaceActivity.class);
			    startActivity(i);*/
			    
		    	finish();
			    
				break;
			}
			
			case R.id.img_Avatar:
			{
				Intent i=new Intent(UpdatePlaceActivity.this,OpenFileActivity.class);
			    // startActivity(i);
			    startActivityForResult(i, FILE_PATH);
				break;
			}
			
			case R.id.edtxt_City:
			{
				edtxtDistrict.setText("");
				edtxtCity.setText("");
				//final Dialog dialog = new Dialog(NewPostActivity.this);
				final Dialog dialog = new Dialog(UpdatePlaceActivity.this);
				dialog.setContentView(R.layout.dialog_province_district);
				dialog.setTitle("Tỉnh - Thành phố");
				dialog.setCanceledOnTouchOutside(true);
                listProvince = (ListView)dialog.findViewById(R.id.list_province_district);
                new LoadProvince().execute();
                
                listProvince.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View
			                view, int position, long id) {
						// TODO Auto-generated method stub
						View vi=view;
				        if(view==null)
				            vi = inflater.inflate(R.layout.item_list_address, null);

				        TextView prov_id = (TextView)vi.findViewById(R.id.tvID);
				        TextView prov_name = (TextView)vi.findViewById(R.id.tvProvinceDistrict);
				        
				        provinceID = prov_id.getText().toString();
				        edtxtCity.setText(prov_name.getText().toString());		
				        
				        dialog.dismiss();
					}
                	
				});
                
                dialog.show();
                
                break;
			}
			
			case R.id.edtxt_Distrist:
			{
				if(provinceID == "")
				{
					final Dialog dialog = new Dialog(UpdatePlaceActivity.this);
	                dialog.setContentView(R.layout.dialog_province_district);
	                dialog.setTitle("Bạn phải chọn tỉnh/thành phố trước");
	                dialog.setCanceledOnTouchOutside(true);
	                dialog.show();
				}
				else
				{
					final Dialog dialog = new Dialog(UpdatePlaceActivity.this);
	                dialog.setContentView(R.layout.dialog_province_district);
	                dialog.setTitle("Quận - Huyện");
	                dialog.setCanceledOnTouchOutside(true);
	                listDistrict = (ListView)dialog.findViewById(R.id.list_province_district);
	                new LoadDistrict().execute();
	                
	                listDistrict.setOnItemClickListener(new OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> parent, View
				                view, int position, long id) {
							// TODO Auto-generated method stub
							View vi=view;
					        if(view==null)
					            vi = inflater.inflate(R.layout.item_list_address, null);

					        TextView dist_id = (TextView)vi.findViewById(R.id.tvID);
					        TextView dist_name = (TextView)vi.findViewById(R.id.tvProvinceDistrict);
					        
					        districtID = dist_id.getText().toString();
					        edtxtDistrict.setText(dist_name.getText().toString());		
					        
					        dialog.dismiss();
						}
	                	
					});
	                
	                dialog.show();
				}
				break;
			}
			
			case R.id.edtxtMapPosition:
			{
				Intent i=new Intent(UpdatePlaceActivity.this,PositionMapActivity.class);
				i.putExtra("longitude",place_longitude);
		        i.putExtra("latitude", place_latitude);
				startActivityForResult(i, LOCATION_MAP);
				break;
			}
			
			case R.id.edtxt_Utility:
			{
				taskDeleteUtilityFinished = false;
				final Dialog dialog = new Dialog(UpdatePlaceActivity.this);
                dialog.setContentView(R.layout.dialog_utility);
                dialog.setTitle("Tiện ích");
                dialog.setCanceledOnTouchOutside(true);
                listUtility = (ListView)dialog.findViewById(R.id.list_Utility);
        		btnAddUtility = (Button) dialog.findViewById(R.id.btn_Add_Utility);
        		btnCloseUtility = (Button) dialog.findViewById(R.id.btn_Close_Utility);
                new LoadUtility().execute();
                
                btnAddUtility.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						selectedUtility = utilityAdapter.getSelectedUtility();
						selectedUtilityID = utilityAdapter.getSelectedUtilityID();
						String temp = "";
						for(String t:selectedUtility)
						{
							temp += t + "; ";
						}
						
						edtxtUtility.setText(temp);
						
						dialog.dismiss();
					}
				});
                
                btnCloseUtility.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				});
                
                dialog.show();
                
                break;
			}
			
			case R.id.edtxt_SpacePlace:
			{
				taskDeleteSpacePlaceFinished = false;
				final Dialog dialog = new Dialog(UpdatePlaceActivity.this);
                dialog.setContentView(R.layout.dialog_utility);
                dialog.setTitle("Không gian địa điểm");
                dialog.setCanceledOnTouchOutside(true);
                listSpacePlace = (ListView)dialog.findViewById(R.id.list_Utility);
        		btnAddUtility = (Button) dialog.findViewById(R.id.btn_Add_Utility);
        		btnCloseUtility = (Button) dialog.findViewById(R.id.btn_Close_Utility);
                new LoadSpacePlace().execute();
                
                btnAddUtility.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						selectedSpacePlace = spacePlaceAdapter.getSelectedSpacePlace();
						selectedSpacePlaceID = spacePlaceAdapter.getSelectedSpacePlaceID();
						String temp = "";
						for(String t:selectedSpacePlace)
						{
							temp += t + "; ";
						}
						
						edtxtSpacePlace.setText(temp);
						
						dialog.dismiss();
					}
				});
                
                btnCloseUtility.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				});
                
                dialog.show();
                
                break;
			}
			
			case R.id.edtxt_GroupCustomer:
			{
				taskDeleteGroupCustomerFinished = false;
				final Dialog dialog = new Dialog(UpdatePlaceActivity.this);
                dialog.setContentView(R.layout.dialog_utility);
                dialog.setTitle("Không gian địa điểm");
                dialog.setCanceledOnTouchOutside(true);
                listGroupCustomer = (ListView)dialog.findViewById(R.id.list_Utility);
        		btnAddUtility = (Button) dialog.findViewById(R.id.btn_Add_Utility);
        		btnCloseUtility = (Button) dialog.findViewById(R.id.btn_Close_Utility);
                new LoadGroupCustomer().execute();
                
                btnAddUtility.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						selectedGroupCustomer = groupCustomerAdapter.getSelectedGroupCustomer();
						selectedGroupCustomerID = groupCustomerAdapter.getSelectedGroupCustomerID();
						String temp = "";
						for(String t:selectedGroupCustomer)
						{
							temp += t + "; ";
						}
						
						edtxtGroupCustomer.setText(temp);
						
						dialog.dismiss();
					}
				});
                
                btnCloseUtility.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				});
                
                dialog.show();
                
                break;
			}
			
			case R.id.edtxt_TimeOpen:
			{
				showDialog(1);
				break;
			}
			
			case R.id.edtxt_TimeClose:
			{
				showDialog(2);
				break;
			}
			
			default: break;
		}
	}
	

	/**
     * Background Async Task to Create new place
     * */
	//Insert new place
    class UpdateInfoPlace extends AsyncTask<String, String, String> {
 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(UpdatePlaceActivity.this);
            pDialog.setMessage("Updating place...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
 
        /**
         * Creating place
         * */
        protected String doInBackground(String... args) {
        	        	
            //String place_name = edtxtPlaceName.getText().toString();
            //String address = edtxtAddress.getText().toString();
            PlaceUpdate pc = new PlaceUpdate(place_id
            								,place_name
            								,address
            								,districtID
            								,place_longitude
            								,place_latitude
            								,phone_number
            								,fax_number
            								,email
            								,website
            								,open_time
            								,close_time
            								,lowest_price
            								,hightest_price
            								,description
            								,avatar_url
            								,avatar_name_random_database);    
            /*PlaceInsert pc = new PlaceInsert(UpdatePlaceActivity.this
					,place_name
					,address);*/
            pc.UpdatePlace();            
            
            return null;
        }
 
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
        	taskUpdatePlaceFinished = true;
            pDialog.dismiss();
			ReturnListPlace();
        } 
    }
    
  //Insert new DetailUtilityPlace
    class CreateDetailUtilityPlace extends AsyncTask<String, String, String> {
 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(UpdatePlaceActivity.this);
            pDialog.setMessage("Updating place...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
 
        /**
         * Creating place
         * */
        protected String doInBackground(String... args) {
            //String place_name = edtxtPlaceName.getText().toString();
            //String address = edtxtAddress.getText().toString();
        	while( taskDeleteUtilityFinished == false )
            {
                try 
                {
                    Thread.sleep(1000);
                } 
                catch (InterruptedException e) 
                {
                    e.printStackTrace();
                }
            }
        	for(int i = 0; i < selectedUtilityID.size(); i++)
			{
				utilityID = selectedUtilityID.get(i);
	        	DetailUtilityPlaceInsert pc = new DetailUtilityPlaceInsert(place_id, utilityID);           
	            pc.InsertDetailUtilityPlace();
			}
            return null;
        }
   
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
        	taskInsertUtilityFinished = true;

			ReturnListPlace();
        } 
    }
    
   //Insert new DetailGroupCustomerPlace
    class CreateDetailGroupCustomerPlace extends AsyncTask<String, String, String> {
 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(UpdatePlaceActivity.this);
            pDialog.setMessage("Updating place...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
 
        /**
         * Creating place
         * */
        protected String doInBackground(String... args) {
            //String place_name = edtxtPlaceName.getText().toString();
            //String address = edtxtAddress.getText().toString();
        	while( taskDeleteGroupCustomerFinished == false )
            {
                try 
                {
                    Thread.sleep(1000);
                } 
                catch (InterruptedException e) 
                {
                    e.printStackTrace();
                }
            }
        	for(int i = 0; i < selectedGroupCustomerID.size(); i++)
			{
				groupCustomerID = selectedGroupCustomerID.get(i);
	        	DetailGroupCustomerPlaceInsert pc = new DetailGroupCustomerPlaceInsert(place_id, groupCustomerID);           
	            pc.InsertDetailGroupCustomerPlace();
			}
            return null;
        }
   
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
        	taskInsertGroupCustomerFinished = true;        	

			ReturnListPlace();
        } 
    }
    
   //Insert new DetailSpacePlace
    class CreateDetailSpacePlace extends AsyncTask<String, String, String> {
 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(UpdatePlaceActivity.this);
            pDialog.setMessage("Updating place...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
 
        /**
         * Creating place
         * */
        protected String doInBackground(String... args) {
            //String place_name = edtxtPlaceName.getText().toString();
            //String address = edtxtAddress.getText().toString();
        	while( taskDeleteSpacePlaceFinished == false )
            {
                try 
                {
                    Thread.sleep(1000);
                } 
                catch (InterruptedException e) 
                {
                    e.printStackTrace();
                }
            }
        	for(int i = 0; i < selectedSpacePlaceID.size(); i++)
			{
				spacePlaceID = selectedSpacePlaceID.get(i);
	        	DetailSpacePlaceInsert pc = new DetailSpacePlaceInsert(place_id, spacePlaceID);           
	            pc.InsertDetailSpacePlace();
			}
            return null;
        }
   
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
        	taskInsertSpacePlaceFinished = true;        	

			ReturnListPlace();
        } 
    }
    
    class CreateComment extends AsyncTask<String, String, String> {
    	 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            /*pDialog = new ProgressDialog(NewPostActivity.this);
            pDialog.setMessage("Creating DetailUtilityPlace...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();*/
        }
 
        /**
         * Creating place
         * */
        protected String doInBackground(String... args) {
        	while( taskUpdatePlaceFinished == false )
            {
                try 
                {
                    Thread.sleep(1000);
                } 
                catch (InterruptedException e) 
                {
                    e.printStackTrace();
                }
            }
        	CommentInsert pc = new CommentInsert(place_id, userid, "", 4);           
	        pc.InsertComment();
            return null;
        }
   
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            //pDialog.dismiss();
        } 
    }
    
  //Insert new DetailUtilityPlace
    class DeleteDetailUtilityPlace extends AsyncTask<String, String, String> {
 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            /*pDialog = new ProgressDialog(UpdatePlaceActivity.this);
            pDialog.setMessage("Creating DetailUtilityPlace...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();*/
        }
 
        /**
         * Creating place
         * */
        protected String doInBackground(String... args) {
            //String place_name = edtxtPlaceName.getText().toString();
            //String address = edtxtAddress.getText().toString();
        	while( taskUpdatePlaceFinished == false )
            {
                try 
                {
                    Thread.sleep(1000);
                } 
                catch (InterruptedException e) 
                {
                    e.printStackTrace();
                }
            }
        	
	        	DetailUtilityPlaceDelete pc = new DetailUtilityPlaceDelete(place_id);           
	            pc.DeleteDetailSpacePlace();
            return null;
        }
   
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            //pDialog.dismiss();
        	taskDeleteUtilityFinished = true;

			ReturnListPlace();
        } 
    }
    
   //Insert new DetailGroupCustomerPlace
    class DeleteDetailGroupCustomerPlace extends AsyncTask<String, String, String> {
 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            /*pDialog = new ProgressDialog(UpdatePlaceActivity.this);
            pDialog.setMessage("Creating DetailUtilityPlace...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();*/
        }
 
        /**
         * Creating place
         * */
        protected String doInBackground(String... args) {
            //String place_name = edtxtPlaceName.getText().toString();
            //String address = edtxtAddress.getText().toString();
        	while( taskUpdatePlaceFinished == false )
            {
                try 
                {
                    Thread.sleep(1000);
                } 
                catch (InterruptedException e) 
                {
                    e.printStackTrace();
                }
            }
        	
	        	DetailGroupCustomerPlaceDelete pc = new DetailGroupCustomerPlaceDelete(place_id);           
	            pc.DeleteDetailGroupCustomerPlace();
            return null;
        }
   
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            //pDialog.dismiss();
        	taskDeleteGroupCustomerFinished = true;        	

			ReturnListPlace();
        } 
    }
    
   //Insert new DetailSpacePlace
    class DeleteDetailSpacePlace extends AsyncTask<String, String, String> {
 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            /*pDialog = new ProgressDialog(UpdatePlaceActivity.this);
            pDialog.setMessage("Creating DetailUtilityPlace...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();*/
        }
 
        /**
         * Creating place
         * */
        protected String doInBackground(String... args) {
            //String place_name = edtxtPlaceName.getText().toString();
            //String address = edtxtAddress.getText().toString();
        	while( taskUpdatePlaceFinished == false )
            {
                try 
                {
                    Thread.sleep(1000);
                } 
                catch (InterruptedException e) 
                {
                    e.printStackTrace();
                }
            }
        	
        	DetailSpacePlaceDelete pc = new DetailSpacePlaceDelete(place_id);           
	        pc.DeleteDetailSpacePlace();
            return null;
        }
   
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            //pDialog.dismiss();
        	taskDeleteSpacePlaceFinished = true;        	

			ReturnListPlace();
        } 
    }
    
    //Load Province
    class LoadProvince  extends AsyncTask<String, String, String>{	  
    	
    	ProvinceLoader provinceloader = new ProvinceLoader();
	    @Override
	    protected void onPreExecute() {
	    	super.onPreExecute();
            pDialog = new ProgressDialog(UpdatePlaceActivity.this);
            pDialog.setMessage("Loading province. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();	       
	    }

		@Override
		protected String doInBackground(String... args) {
			provincesList = provinceloader.GetProvince();
			return null;
	    }

	    //*//**
	    // * After completing background task Dismiss the progress dialog
	    // * **//*
	    protected void onPostExecute(String file_url) {
	    	pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					provinceAdapter = new ProvinceAdapter(UpdatePlaceActivity.this, provinceloader, provincesList);
					//adapter = new PlaceAdapter(ListPlaceActivity.this, placeload);
					listProvince.setAdapter(provinceAdapter);		        
			       
				}
			});
	    }
	}
    
    //Load district
    class LoadDistrict extends AsyncTask<String, String, String>{	  
    	
    	DistrictLoader districtloader = new DistrictLoader(provinceID);
	    @Override
	    protected void onPreExecute() {
	    	super.onPreExecute();
            pDialog = new ProgressDialog(UpdatePlaceActivity.this);
            pDialog.setMessage("Loading districts. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();	       
	    }

		@Override
		protected String doInBackground(String... args) {
			districtsList = districtloader.GetDistrict();
			return null;
	    }

	    //*//**
	    // * After completing background task Dismiss the progress dialog
	    // * **//*
	    protected void onPostExecute(String file_url) {
	    	pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					districtAdapter = new DistrictAdapter(UpdatePlaceActivity.this, districtloader, districtsList);
					//adapter = new PlaceAdapter(ListPlaceActivity.this, placeload);
					listDistrict.setAdapter(districtAdapter);		        
			       
				}
			});
	    }
	}
    
    //Load utility
    class LoadUtility extends AsyncTask<String, String, String>{	  
    	
    	UtilityLoader utilityloader = new UtilityLoader();
	    @Override
	    protected void onPreExecute() {
	    	super.onPreExecute();
            pDialog = new ProgressDialog(UpdatePlaceActivity.this);
            pDialog.setMessage("Loading utility. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();	       
	    }

		@Override
		protected String doInBackground(String... args) {
			utilitysList = utilityloader.GetUtility();
			return null;
	    }

	    //*//**
	    // * After completing background task Dismiss the progress dialog
	    // * **//*
	    protected void onPostExecute(String file_url) {
	    	pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {					
					utilityAdapter = new UtilityAdapter(UpdatePlaceActivity.this, utilityloader, utilitysList);
					listUtility.setAdapter(utilityAdapter);				       
				}
			});
	    }
	}    

    //Load space place
    class LoadSpacePlace extends AsyncTask<String, String, String>{	  
    	
    	SpacePlaceLoader spaceplaceloader = new SpacePlaceLoader();
	    @Override
	    protected void onPreExecute() {
	    	super.onPreExecute();
            pDialog = new ProgressDialog(UpdatePlaceActivity.this);
            pDialog.setMessage("Loading space place. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();	       
	    }

		@Override
		protected String doInBackground(String... args) {
			spaceplacesList = spaceplaceloader.GetSpacePlace();
			return null;
	    }

	    //*//**
	    // * After completing background task Dismiss the progress dialog
	    // * **//*
	    protected void onPostExecute(String file_url) {
	    	pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {					
					spacePlaceAdapter = new SpacePlaceAdapter(UpdatePlaceActivity.this, spaceplaceloader, spaceplacesList);
					listSpacePlace.setAdapter(spacePlaceAdapter);				       
				}
			});
	    }
	}    

    //Load group customer
    class LoadGroupCustomer  extends AsyncTask<String, String, String>{	  
		GroupCustomerLoader groupcustomeroader = new GroupCustomerLoader();
	    @Override
	    protected void onPreExecute() {
	    	super.onPreExecute();
	        pDialog = new ProgressDialog(UpdatePlaceActivity.this);
	        pDialog.setMessage("Loading group customer. Please wait...");
	        pDialog.setIndeterminate(false);
	        pDialog.setCancelable(false);
	        pDialog.show();	       
	    }
	
		@Override
		protected String doInBackground(String... args) {
			groupcustomersList = groupcustomeroader.GetGroupCustomer();
			return null;
	    }
	
	    //*//**
	    // * After completing background task Dismiss the progress dialog
	    // * **//*
	    protected void onPostExecute(String file_url) {
	    	pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {					
					groupCustomerAdapter = new GroupCustomerAdapter(UpdatePlaceActivity.this, groupcustomeroader, groupcustomersList);
					listGroupCustomer.setAdapter(groupCustomerAdapter);				       
				}
			});
	    }
	}
    
  //Upload image
    class UploadImage  extends AsyncTask<String, String, String>{	  
		GroupCustomerLoader groupcustomeroader = new GroupCustomerLoader();
	    @Override
	    protected void onPreExecute() {
	    	super.onPreExecute();
	       /* pDialog = new ProgressDialog(UpdatePlaceActivity.this);
	        pDialog.setMessage("Loading group customer. Please wait...");
	        pDialog.setIndeterminate(false);
	        pDialog.setCancelable(false);
	        pDialog.show();	 */      
	    }
	
		@Override
		protected String doInBackground(String... args) {
			/*new Thread(new Runnable() {
                public void run() {
                     runOnUiThread(new Runnable() {
                            public void run() {
                                messageText.setText("uploading started.....");
                            }
                        }); */                     
			while( taskUpdatePlaceFinished == false || taskInsertGroupCustomerFinished == false
					|| taskUpdatePlaceFinished == false || taskInsertSpacePlaceFinished == false)
            {
                try 
                {
                    Thread.sleep(1000);
                } 
                catch (InterruptedException e) 
                {
                    e.printStackTrace();
                }
            } 
            uploadFile(avatar_path + "" + avatar_name);
                                              
               /* }
              }).start();*/	
			return null;
	    }
	
	    //*//**
	    // * After completing background task Dismiss the progress dialog
	    // * **//*
	    protected void onPostExecute(String file_url) {
	    	pDialog.dismiss();
			// updating UI from Background Thread
	    }
	}
    
    class LoadDetailPlaceAsync extends AsyncTask<String, String, String>
    {
    	PlaceDetailLoader placedetailloader = new PlaceDetailLoader(place_id);
    	@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(UpdatePlaceActivity.this);
			pDialog.setMessage("Loading places. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}
    	
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
	    	//placeload = new PlaceLoader();
			
			place = placedetailloader.GetPlace();
			return null;
		}
		
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {					
			        Url_avatar = place.get(placedetailloader.TAG_URL_AVATAR) + place.get(placedetailloader.TAG_NAME_AVATAR);
			        // Setting all values in listview
			        edtxtPlaceName.setText( place.get(placedetailloader.TAG_PLACE_NAME));
			        edtxtAddress.setText(place.get(placedetailloader.TAG_ADDRESS));
			        edtxtCity.setText(place.get(placedetailloader.TAG_PROVINCE_NAME));
			        edtxtDistrict.setText(place.get(placedetailloader.TAG_DISTRICT_NAME));
			        edtxtMapPosition.setText(place.get(placedetailloader.TAG_LATITUDE) + " - " + place.get(placedetailloader.TAG_LONGITUDE));
			        edtxtPhone.setText(place.get(placedetailloader.TAG_PHONE_NUMBER));			        
			        edtxtFax.setText(place.get(placedetailloader.TAG_FAX_NUMBER));			        			        
			        edtxtEmail.setText(place.get(placedetailloader.TAG_EMAIL));
			        edtxtWebsite.setText(place.get(placedetailloader.TAG_WEBSITE));			        
			        edtxtTimeOpen.setText(place.get(placedetailloader.TAG_OPEN_TIME));
			        edtxtTimeClose.setText(place.get(placedetailloader.TAG_CLOSE_TIME));			        
			        edtxtLowPrice.setText(place.get(placedetailloader.TAG_LOWEST_PRICE));			        
			        edtxtHightPrice.setText(place.get(placedetailloader.TAG_HIGHTEST_PRICE));
			        if(!place.get(placedetailloader.TAG_UTILITY).equals("null"))
			        	edtxtUtility.setText(place.get(placedetailloader.TAG_UTILITY));
			        if(!place.get(placedetailloader.TAG_SPACE_PLACE).equals("null"))
			        	edtxtSpacePlace.setText(place.get(placedetailloader.TAG_SPACE_PLACE));
			        if(!place.get(placedetailloader.TAG_GROUP_CUSTOMER).equals("null"))
			        	edtxtGroupCustomer.setText(place.get(placedetailloader.TAG_GROUP_CUSTOMER));
			        edtxtDescription.setText(place.get(placedetailloader.TAG_DESCRIPTION));
			        
			        imageLoader.DisplayImage(Url_avatar , imgAvatar);
			        
			        districtID = place.get(placedetailloader.TAG_DISTRICT_ID);
			        place_longitude = place.get(placedetailloader.TAG_LONGITUDE);
			        place_latitude = place.get(placedetailloader.TAG_LATITUDE);
			        open_time = place.get(placedetailloader.TAG_OPEN_TIME);
			        close_time = place.get(placedetailloader.TAG_CLOSE_TIME);
			        avatar_url = place.get(placedetailloader.TAG_URL_AVATAR);
			        avatar_name_random_database = place.get(placedetailloader.TAG_NAME_AVATAR);
				}
			});

		}
    }

    //Upload photo
    public int uploadFile(String sourceFileUri) {
    	String fileName = sourceFileUri;
	
	    HttpURLConnection conn = null;
	    DataOutputStream dos = null;  
	    String lineEnd = "\r\n";
	    String twoHyphens = "--";
	    String boundary = "*****";
	    int bytesRead, bytesAvailable, bufferSize;
	    byte[] buffer;
	    int maxBufferSize = 1 * 1024 * 1024; 
	    File sourceFile = new File(sourceFileUri); 
	     
	    try {
			sourceFile.createNewFile();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	    
	  //Convert bitmap to byte array
	    
	    Bitmap resized = Bitmap.createScaledBitmap(bmp,(int)(bmp.getWidth()/2), (int)(bmp.getHeight()/2), true);

	    OutputStream fOut = null;
        try {
			fOut = new FileOutputStream(sourceFile);

	        resized.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
	        try {
				fOut.flush();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        try {
				fOut.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	    
	    
	    if (!sourceFile.isFile()) {
	            
	    	dialog.dismiss(); 
	              
	        Log.e("uploadFile", "Source File not exist :"
	                                 +avatar_path + "" + avatar_name);
	              
	        runOnUiThread(new Runnable() {
	        	public void run() {
	       
	                	 messageText.setText("Source File not exist :"
	                             +avatar_path + "" + avatar_name);
	                 }
	             }); 
	              
	        return 0;
	          
	    }
	    else
        {
             try { 
                  
                   // open a URL connection to the Servlet
                 FileInputStream fileInputStream = new FileInputStream(sourceFile);
                 URL url = new URL(upLoadServerUri);
                  
                 // Open a HTTP  connection to  the URL
                 conn = (HttpURLConnection) url.openConnection(); 
                 conn.setDoInput(true); // Allow Inputs
                 conn.setDoOutput(true); // Allow Outputs
                 conn.setUseCaches(false); // Don't use a Cached Copy
                 conn.setRequestMethod("POST");
                 conn.setRequestProperty("Connection", "Keep-Alive");
                 conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                 conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                 conn.setRequestProperty("uploaded_file", fileName); 
                                  
                 dos = new DataOutputStream(conn.getOutputStream());
        
                 dos.writeBytes(twoHyphens + boundary + lineEnd); 
                 dos.writeBytes("Content-Disposition: form-data; name= 'uploaded_file';filename='"
                                           + avatar_name_random + ".png'" + lineEnd); //can change name here <=======
                  
                 dos.writeBytes(lineEnd);
        
                 // create a buffer of  maximum size
                 bytesAvailable = fileInputStream.available(); 
        
                 bufferSize = Math.min(bytesAvailable, maxBufferSize);
                 buffer = new byte[bufferSize];
        
                 // read file and write it into form...
                 bytesRead = fileInputStream.read(buffer, 0, bufferSize);  
                    
                 while (bytesRead > 0) {
                      
                   dos.write(buffer, 0, bufferSize);
                   bytesAvailable = fileInputStream.available();
                   bufferSize = Math.min(bytesAvailable, maxBufferSize);
                   bytesRead = fileInputStream.read(buffer, 0, bufferSize);   
                    
                  }
        
                 // send multipart form data necesssary after file data...
                 dos.writeBytes(lineEnd);
                 dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        
                 // Responses from the server (code and message)
                 serverResponseCode = conn.getResponseCode();
                 String serverResponseMessage = conn.getResponseMessage();
                   
                 Log.i("uploadFile", "HTTP Response is : "
                         + serverResponseMessage + ": " + serverResponseCode);
                  
                 if(serverResponseCode == 200){
                      
                     runOnUiThread(new Runnable() {
                          public void run() {
                               
                             String msg = "File Upload Completed.";
                               
                              messageText.setText(msg);
                             /* Toast.makeText(UpdatePlaceActivity.this, "File Upload Complete.", 
                                           Toast.LENGTH_SHORT).show();*/
                          }
                      });                
                 }    
                  
                 //close the streams //
                 fileInputStream.close();
                 dos.flush();
                 dos.close();
                   
            } catch (MalformedURLException ex) {
                 
                dialog.dismiss();  
                ex.printStackTrace();
                 
                runOnUiThread(new Runnable() {
                    public void run() {
                        messageText.setText("MalformedURLException Exception : check script url.");
                        Toast.makeText(UpdatePlaceActivity.this, "MalformedURLException", 
                                                            Toast.LENGTH_SHORT).show();
                    }
                });
                 
                Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
            } catch (Exception e) {
                 
                dialog.dismiss();  
                e.printStackTrace();
                 
                runOnUiThread(new Runnable() {
                    public void run() {
                        messageText.setText("Got Exception : see logcat ");
                        Toast.makeText(UpdatePlaceActivity.this, "Got Exception : see logcat ", 
                                Toast.LENGTH_SHORT).show();
                    }
                });
                Log.e("Upload file to server Exception", "Exception : "
                                                 + e.getMessage(), e);  
            }
            dialog.dismiss(); 
			taskUploadAvatarFinished = true;
			
			ReturnListPlace();
			
            return serverResponseCode; 
             
         } // End else block 
	 } 	
    
    void ReturnListPlace()
    {
    	if(taskInsertGroupCustomerFinished == true &&
    			taskUpdatePlaceFinished == true &&
				taskInsertSpacePlaceFinished == true &&
				taskInsertUtilityFinished == true &&
				taskUploadAvatarFinished == true)
		{
			 Intent i=new Intent(UpdatePlaceActivity.this,ListPlaceActivity.class);
		     startActivity(i);
		}
    }


}
